package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    /**
     * 根据spdId查询商品详情
     * @param id    spuId
     * @return      Map
     */
    public Map<String, Object> loadItemData(Long id) {
        //查询spu
        SpuDTO spuDTO = itemClient.querySpuById(id);
        //查询分类
        List<CategoryDTO> categorys = itemClient.queryCategoryByIds(spuDTO.getCategoryIds());
        //查询品牌
        BrandDTO brandDTO = itemClient.queryBrandById(spuDTO.getBrandId());
        //根据spuid查询detail
        SpuDetailDTO spuDetailDTO = itemClient.querySpuDetailBySpuId(id);
        //根据spuid查询sku集合
        List<SkuDTO> skuDTOList = itemClient.querySkuListBySpuId(id);
        //查询规格
        List<SpecGroupDTO> groupDTOList = itemClient.querySpecByCategoryId(spuDTO.getCid3());

        Map<String, Object> data = new HashMap<>();
        data.put("categories", categorys); // 三级分类的对象集合
        data.put("brand", brandDTO);      // 品牌对象
        data.put("spuName", spuDTO.getName());    // 来自于SpuDTO
        data.put("subTitle", spuDTO.getSubTitle());   // 来自于SpuDTO
        data.put("skus", skuDTOList);       // sku集合
        data.put("detail", spuDetailDTO);     // SpuDetail对象
        data.put("specs", groupDTOList);      // 规格组集合，每个规格组中有个规格参数的集合

        return data;
    }

    //生成静态化页面模板引擎
    @Autowired
    private SpringTemplateEngine templateEngine;
    @Value("${ly.static.itemDir}")
    private String itemDir;
    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    /**
     * 根据spuId生成静态化页面
     * @param spuId spuId
     */
    public void createStaticHtml(Long spuId){
        //上下文对象
        Context context = new Context();
        //值内容(Map集合)(直接调用上面的方法就好)
        context.setVariables(loadItemData(spuId));
        //文件流
        File dir = new File(itemDir);
        if (!dir.exists()){
            dir.mkdirs();
            if (!dir.mkdirs()){
                log.error("[静态页服务异常] 创建目录失败: " + itemDir);
                throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
            }
        }
        File file = new File(dir,spuId + ".html");

        try (PrintWriter writer = new PrintWriter(file,"UTF-8")){
            /**
             * 引擎生成静态化页
             * Param1:  模板名称
             * Param2:  上下文: 封装填充模板所有数据
             * Param3:  文件流
             */
            templateEngine.process(itemTemplate, context, writer);
        } catch (Exception e){
            log.error("[静态页服务异常]" + e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * 删除静态页
     * @param spuId
     */
    public void deleteStaticHtml(Long spuId) {
        String fileName = spuId + ".html";
        File file = new File(itemDir, fileName);
        if (file.exists()){
            boolean delete = file.delete();
            if (!delete){
                //删除失败
                log.error("[静态页服务] 删除文件失败 {}",fileName);
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
        }
    }
}
